from flask import Blueprint,request,g
from model.model import *
from db_init import db
import re,json
from datetime import datetime,date
from tools.catch import item2dict

user = Blueprint('/user',__name__,url_prefix='/user')

@user.route('/register',methods=['post'])
def user_reg():
    name = request.form.get('name')
    password = request.form.get('password')
    mobile = request.form.get('mobile')
    if not all([name,password,mobile]):
        return {'msg':'前端数据不完整','code':400}
    if not re.search(r'^1[3-9]\d{9}$',mobile):
        return {'msg':'手机号格式不对','code':400}
    user = User(name=name,password=password,mobile=mobile)
    db.session.add(user)
    db.session.commit()
    return '注册成功'

@user.route('/login',methods=['post'])
def user_login():
    # db.session.add(User_log(user_id,'/user_login',time))
    # db.session.commit()
    password = request.form.get('password')
    mobile = request.form.get('mobile')
    if not re.search(r'^1[3-9]\d{9}$',mobile):
        return {'msg':'手机号格式不对','code':400}
    if not all([password,mobile]):
        return {'msg':'前端数据不对','code':400}
    user = User.query.filter_by(mobile=mobile).first()
    if not user:
        return {'msg':'请先注册!','code':200}
    if user.password == password:
        # 通过用户找对应角色
        # 通过角色找对应权限
        # 把用户信息，权限信息组合发给前端
        # roles = user.role_id
        # role_list = []
        # power_list = {}
        # for i in roles:
        #     power = i.power
        #     role_list.append({'id':i.id,'name':i.name})
        #     for j in power:
        #         power_list[j.id] = {'id':j.id,'name':j.name,'url':j.url,'method':j.method}
        # user_info = {'id':user.id,'name':user.name}
        # user_power = user_info.copy()
        # user_power['power'] = power_list
        # return {'msg':'登陆成功','data':role_list,'data1':user_power}
        powers = sum([role.power for role in user.role_id],[])
        return {'name':user.name,'power':{item.get('id'):item for item in item2dict(powers)}}
    else:
        return '密码错误'

@user.route('/qian',methods={'POST'})
def user_qian():
    uid = request.args.get('uid')
    check_data =  CheckIn.query.filter_by(user_id=uid).first()
    today = date.today()
    if not check_data:
        db.session.add(CheckIn(user_id=uid,status=True,check_data=date.today()))
    elif check_data.check_data >= today:
        return '今天已经签到'
    else:
        # check_data.status = True
        check_data.check_data = today
    db.session.commit()
    return {'msg':'签到成功','code':200}

@user.route('/checktass',methods=['get'])
def check_tast():
    CheckIn.query.update({'status': False})
    db.session.commit()
    return {'msg':'更新成功','code':200}


